package com.huhao.smark;

import static com.huhao.smark.Config.*;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class DetailActivity extends AppCompatActivity {

    private TextView tvId, tvType, tvCategory, tvAmount, tvDescription, tvDate, tvAddTime, tvUpdateTime;
    private Button btnEdit, btnDelete;
    private int recordId; // 存储当前记录ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        // 初始化视图
        tvId = findViewById(R.id.tv_id);
        tvType = findViewById(R.id.tv_type);
        tvCategory = findViewById(R.id.tv_category);
        tvAmount = findViewById(R.id.tv_amount);
        tvDescription = findViewById(R.id.tv_description);
        tvDate = findViewById(R.id.tv_date);
        tvAddTime = findViewById(R.id.tv_add_time);
        tvUpdateTime = findViewById(R.id.tv_update_time);

        // 初始化按钮
        btnEdit = findViewById(R.id.btn_edit);
        btnDelete = findViewById(R.id.btn_delete);

        // 获取传递的记录ID
        recordId = getIntent().getIntExtra("recordId", -1);

        if (recordId != -1) {
            loadRecordDetail(recordId);
        }

        // 编辑按钮点击事件
        btnEdit.setOnClickListener(v -> showEditDialog());

        // 删除按钮点击事件
        btnDelete.setOnClickListener(v -> showDeleteConfirmation());
    }

    private void loadRecordDetail(int recordId) {
        // 获取 token
        SharedPreferences prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);
        String token = prefs.getString("token", "");

        if (token.isEmpty()) {
            finish();
            return;
        }

        // 构建请求 URL
        String url = BASE_URL + ADD_RECORD + "/" + recordId;

        // 创建请求
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    // 处理失败情况
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                runOnUiThread(() -> {
                    try {
                        if (response.isSuccessful()) {
                            JSONObject json = new JSONObject(responseData);
                            if (json.getBoolean("success")) {
                                JSONObject data = json.getJSONObject("data");

                                // 更新 UI
                                tvId.setText(String.valueOf(data.getInt("id")));
                                tvType.setText(data.getInt("type") == 0 ? "收入" : "支出");
                                tvCategory.setText(data.getString("category"));
                                tvAmount.setText("¥" + data.getDouble("price"));
                                tvDescription.setText(data.getString("remark"));
                                tvDate.setText(data.getString("bookDate"));
                                tvAddTime.setText(data.getString("addTime"));
                                tvUpdateTime.setText(data.getString("updateTime"));
                            } else {
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        finish();
                    }
                });
            }
        });
    }

    // 显示编辑对话框
    private void showEditDialog() {
        // 从TextView获取当前数据
        String category = tvCategory.getText().toString();
        String amount = tvAmount.getText().toString().replace("¥", "");
        String description = tvDescription.getText().toString();
        int currentType = tvType.getText().toString().equals("收入") ? 0 : 1;

        // 加载自定义布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit_record, null);

        // 初始化视图
        RadioGroup rgType = dialogView.findViewById(R.id.rg_type);
        RadioButton rbIncome = dialogView.findViewById(R.id.rb_income);
        RadioButton rbExpense = dialogView.findViewById(R.id.rb_expense);
        EditText etCategory = dialogView.findViewById(R.id.et_category);
        EditText etAmount = dialogView.findViewById(R.id.et_amount);
        EditText etDescription = dialogView.findViewById(R.id.et_description);

        // 设置当前值
        if (currentType == 0) {
            rbIncome.setChecked(true);
        } else {
            rbExpense.setChecked(true);
        }
        etCategory.setText(category);
        etAmount.setText(amount);
        etDescription.setText(description);

        // 创建对话框
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("编辑记录")
                .setView(dialogView)
                .setPositiveButton("保存", null)
                .setNegativeButton("取消", null)
                .create();

        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                // 获取用户输入
                int selectedType = rgType.getCheckedRadioButtonId() == R.id.rb_income ? 0 : 1;
                String inputCategory = etCategory.getText().toString().trim();
                String inputAmount = etAmount.getText().toString().trim();
                String inputDescription = etDescription.getText().toString().trim();

                // 验证输入
                if (inputCategory.isEmpty()) {
                    etCategory.setError("请输入类别");
                    return;
                }

                if (inputAmount.isEmpty()) {
                    etAmount.setError("请输入金额");
                    return;
                }

                try {
                    double amountValue = Double.parseDouble(inputAmount);
                    if (amountValue <= 0) {
                        etAmount.setError("金额必须大于0");
                        return;
                    }
                } catch (NumberFormatException e) {
                    etAmount.setError("请输入有效的金额");
                    return;
                }

                // 构建JSON请求体
                JSONObject json = new JSONObject();
                try {
                    json.put("type", selectedType);
                    json.put("category", inputCategory);
                    json.put("price", inputAmount);
                    json.put("remark", inputDescription);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(DetailActivity.this, "数据格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 发送更新请求
                updateRecord(recordId, json.toString());
                dialog.dismiss();
            });
        });

        dialog.show();
    }

    // 更新记录
    private void updateRecord(int recordId, String jsonBody) {
        SharedPreferences prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);
        String token = prefs.getString("token", "");
        String url = BASE_URL + ADD_RECORD + "/" + recordId;

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(url)
                .put(body)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(DetailActivity.this, "更新失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(() -> {
                    if (response.isSuccessful()) {
                        Toast.makeText(DetailActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        loadRecordDetail(recordId); // 刷新数据
                    } else {
                        Toast.makeText(DetailActivity.this, "修改失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 删除确认对话框
    private void showDeleteConfirmation() {
        new AlertDialog.Builder(this)
                .setTitle("删除记录")
                .setMessage("确定要删除这条记录吗？")
                .setPositiveButton("删除", (dialog, which) -> deleteRecord(recordId))
                .setNegativeButton("取消", null)
                .show();
    }

    // 删除记录
    private void deleteRecord(int recordId) {
        SharedPreferences prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);
        String token = prefs.getString("token", "");
        String url = BASE_URL + ADD_RECORD + "/" + recordId;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(DetailActivity.this, "删除失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(() -> {
                    if (response.isSuccessful()) {
                        Toast.makeText(DetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        finish(); // 关闭当前界面
                    } else {
                        Toast.makeText(DetailActivity.this, "删除失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}